package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.atguigu.gmall.cart.service.CartInfoAsyncService;
import com.atguigu.gmall.model.cart.CartInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/*购物车中 创建新线程的实现类*/

@Service
public class CartInfoAsyncServiceImpl implements CartInfoAsyncService {


    @Autowired
    private CartInfoMapper cartInfoMapper;


    //Mysql更新购物车   打异步注解的方式   异步保存  异步调用
    @Override
    @Async
    public void updateByIdAsync(CartInfo cartInfo) {
        //cartInfoMapper.updateById(cartInfo);

        //运行时会报错，因为缓存中是没有数据库的主键的，所以在向数据库更新数据时，可能会漏数据，因此不能使用主键作为条件查询，需要使用混合条件
        cartInfoMapper.update(cartInfo,new QueryWrapper<CartInfo>()
                .eq("user_id",cartInfo.getUserId())
                .eq("sku_id",cartInfo.getSkuId()));
    }


    @Override
    @Async
    public void insertAsync(CartInfo cartInfo) {
        System.out.println("Async:" + Thread.currentThread().getName());
        cartInfoMapper.insert(cartInfo);
    }


    @Override
    @Async
    public void updateByIdAsyncExt(String userTempId, String userId) {
        System.out.println("Async:updateByIdAsyncExt:" + Thread.currentThread().getName());
        CartInfo cartInfo = new CartInfo();
        cartInfo.setUserId(userId);
        cartInfoMapper.update(cartInfo,new QueryWrapper<CartInfo>()
                .eq("user_id",userTempId));
    }

    //删除
    @Override
    @Async
    public void deleteByUserTempId(String userTempId) {
        System.out.println("Async:deleteByUserTempId:" + Thread.currentThread().getName());
        cartInfoMapper.delete(new QueryWrapper<CartInfo>()
                .eq("user_id",userTempId));
    }
}
